﻿using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;

namespace Inovout.Web.Http
{
    public class BlobMediaTypeFormatter : MediaTypeFormatter
    {
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger));

        }
        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            //todo:以后改成BUFFER来读。
            byte[] buffer = new byte[readStream.Length];
            string base64String = UTF8Encoding.UTF8.GetString(buffer);


            byte[] decodedBytes = Convert.FromBase64String(base64String);
            Stream stream = new MemoryStream();
            stream.Write(decodedBytes, 0, decodedBytes.Length);
            stream.Position = 0;
            return stream;
        }
        public override bool CanReadType(Type type)
        {
            return type.IsAssignableFrom(typeof(Stream));
        }

        public override bool CanWriteType(Type type)
        {
            return false;
        }
    }
}
